﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Telerik.Windows.Controls;
using System.Windows.Interactivity;
using Telerik.Windows.Controls.GridView;
using NetBay.Core.BusinessEntities.Workflow;
using System.Windows.Data;
using Rio.Framework.Pages.Helpers.Converter;

namespace Rio.Framework.Pages.AppCode.Helpers.Behavior
{
    public class IsVisibleBehavior : Behavior<RadGridView>
    {
        private IValueConverter converter = new WorkflowStateToVisibility();

        public string WorkflowStatePropertyName
        {
            get { return (string)GetValue(WorkflowStatePropertyNameProperty); }
            set { SetValue(WorkflowStatePropertyNameProperty, value); }
        }
        public static readonly DependencyProperty WorkflowStatePropertyNameProperty =
            DependencyProperty.Register("WorkflowStatePropertyName", typeof(string), typeof(IsVisibleBehavior), new PropertyMetadata(null));

        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.RowLoaded += AssociatedObject_RowLoaded;
            this.AssociatedObject.RowUnloaded += AssociatedObject_RowUnloaded;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            this.AssociatedObject.RowLoaded -= AssociatedObject_RowLoaded;
            this.AssociatedObject.RowUnloaded -= AssociatedObject_RowUnloaded;
        }

        private void AssociatedObject_RowLoaded(object sender, Telerik.Windows.Controls.GridView.RowLoadedEventArgs e)
        {
            var row = e.Row as GridViewRow;

            if (row != null)
            {
                WorkflowDocument ds = row.DataContext as WorkflowDocument;

                if (ds.DocumentStatus == WorkflowState.None)
                {
                    row.IsExpandable = false;
                }
                else
                {
                    row.IsExpandable = true;
                }

                //rokw.SetBinding(GridViewRow.IsExpandableProperty, new Binding(this.WorkflowStatePropertyName) { Converter = converter });
            }
        }

        private void AssociatedObject_RowUnloaded(object sender, Telerik.Windows.Controls.GridView.RowUnloadedEventArgs e)
        {
            var row = e.Row as GridViewRow;

            if (row != null)
            {
                //BindingOperations. ClearBinding(row, GridViewRow.IsExpandableProperty);

                
            }
        }
    }
}
